<template>
  <div class="app-view-container">
    <mu-appbar class="app-popup-topbar" :title="texts.title">
      <mu-raised-button class="size-s" label="取消" slot="left" @click.native="cancel()"/>
      <mu-raised-button class="size-s" label="确认" slot="right" primary  @click.native="updateData()"/>
    </mu-appbar>
    <div class="app-popup-content">
      <vue-form :state="formstate">
        <mu-list class="app-list">
          <validate>
            <mu-text-field hintText="请输入标题" name="memorabiliaTitle" v-model="itemData.memorabiliaTitle" fullWidth :underlineShow="false" class="item-insert" required='required' :errorText="showError?matchError(formstate,'title',{required:'必填'}):''"/>
          </validate>
          <mu-divider/>
          <mu-list-item title="发生日期" @click="$refs.label_start.click()">
            <label slot="after" ref="label_start" class="datetime-label">{{dateFormat(itemData.occurredTime,'YYYY-MM-DD 星期w')}}<mu-icon value="date_range" class="icon_date"/><mu-date-picker class="item-hidden-input" v-model="itemData.occurredTime"/></label>
          </mu-list-item>
          <mu-divider/>
          <mu-list-item @click="itemData.status=!itemData.status" title="开放状态">
            <mu-switch v-model="itemData.status"  slot="right"/>
          </mu-list-item>
        </mu-list>
        <mu-list class="app-list">
          <mu-sub-header>描述</mu-sub-header>
          <mu-text-field hintText="请输入描述" name="memorabiliaText" v-model="itemData.memorabiliaText" fullWidth multiLine :underlineShow="false" :rows="2" :rowsMax="5" class="item-insert"/>
        </mu-list>
        <mu-list class="app-list">
          <mu-sub-header>附件（共{{fileListState[itemData.id]==null?0:(fileListState[itemData.id]['list']==null?0:fileListState[itemData.id]['list'].length)}}个）</mu-sub-header>
          <my-webuploader :rotatable="false" :config="{
            server:texts.baseUrl+(this.$route.params.action=='add'?texts.uploadUrlAdd:texts.uploadUrlEdit),
            formData:{
              memoId:this.$route.params.data?this.$route.params.data.id:null,
              familyId:this.$route.params.data?this.$route.params.data.familyId:null,
              ucode:this.$route.params.ucode?this.$route.params.ucode:null
            }
            }" @uploadSuccess="uploadSuccess" @uploadFinished="uploadFinished"></my-webuploader>
          <bigevent-file-list v-if="typeof fileListState[itemData.id]!=='undefined'" v-show="fileListState[itemData.id]&&fileListState[itemData.id].show"  @click="handleFileClick" :list="fileListState[itemData.id]?fileListState[itemData.id].list:[]"></bigevent-file-list>
          <div class="file-loading" v-if="fileListState[itemData.id]&&fileListState[itemData.id].loading">文件加载中</div>
        </mu-list>
      </vue-form>
    </div>
  </div>
</template>

<script>
import {dateFormat} from 'scripts/common'
import LunarCalendar from 'scripts/LunarCalendar'
import textImgBox from 'components/textImgBox'

//大事件文件列表
import {bigeventFileList} from '../components/fileList'

import services from 'services'
export default {
  data () {
    return {
      texts:{"title":'添加大事件',"baseUrl":'http://localhost:8090',"uploadUrlAdd":'/fda/memorabilia/upload.do',"uploadUrlEdit":'/fda/memorabilia/uploadMemoFile.do'},
      fileListState:{},
      itemData:{"id":'',"memorabiliaNo":'',"memorabiliaTitle":'',"memorabiliaText":'',"occurredTime":'',"status":true,"familyId":'',"createBy":'',"updateBy":'',"createTime":'',"sort":''},
      // fileCategorys:[],
      showInput:{},
      formstate:{},
      showError:false
    }
  },
  computed:{
    /*cateNameList (){
      return this.fileCategorys.map(function(x){return {label:x.name,nativeValue:x.name} })
    },
    lunarObj (){
      return LunarCalendar.solar2lunar(new Date(this.itemData.occurredTime).getFullYear(),new Date(this.itemData.occurredTime).getMonth()+1,new Date(this.itemData.occurredTime).getDate())
    }*/
  },
  components:{
    "text-img-box":textImgBox,
    "bigevent-file-list":bigeventFileList,
    "my-webuploader":(resolve)=>{require(['components/myWebuploader/myWebuploader'],resolve)}
  },
  mounted () {
    for (var i=1; i <= 2; i++) {
     this.$set(this.showInput,'ipt'+i,false);
    }
    this.getData()
  },
  beforeRouteUpdate (to,form,next){
    this.getData();
    next()
  },
  methods: {
    getData (){
      if (this.$route.params.action=='edit') {
        if(this.$route.params.data!=null){
          //设置大事件信息
          this.itemData=this.$route.params.data;
          this.itemData.status=(this.itemData.status==1?true:false);
          this.itemData.occurredTime=dateFormat(this.itemData.occurredTime,'YYYY-MM-DD');
          //设置编辑页面参数
          this.texts.title='编辑大事件';
        }
        //获取大事件附件信息
        this.getFileData(this.itemData.id,this.itemData.familyId);
        /*var vm=this
        //TODO 获取大事件信息
        services.BigEventService.getMemos({
          data:{
            id: vm.$route.params.id
          },
          success:(data)=>{
            vm.itemData=data
            vm.itemData.occurredTime=dateFormat(vm.itemData.occurredTime,'YYYY-MM-DD')
          }
        })*/
      }
    },
    handleFileClick (fileData){
      //下载文件
      services.BigEventService.downMemoFile({
        data:{
          fileId:fileData.id
        },
        success:(data)=>{
          console.log('download success in bigeventEdit.vue');
        }
      })
      //点击下载文件
      // alert(JSON.stringify(fileData));
    },
    getFileData (id,familyId){
      var vm=this
      if(!this.fileListState[id]){
        this.$set(this.fileListState,id,{show:false,loading:true})
        //获取文件列表
        services.BigEventService.getMemoFile({
          data:{
            id:id,
            familyId:familyId
          },
          success:(data)=>{
            vm.$set(vm.fileListState[id],'list',data)
          },
          complete:()=>{
            vm.$set(vm.fileListState[id],'loading',false)
          }
        })
      }
      this.$set(this.fileListState[id],'show',!this.fileListState[id].show)
    },
    cancel (){
      this.$root.$router.back()
    },
    updateData (){
      var vm=this
      if (vm.formstate.$invalid) {
        vm.showError=true
        return
      } 
      vm.setLoading(true)
      //更新大事件信息
      services.BigEventService.updateMemo({
        data:{
          //memo
          id:vm.itemData.id,
          memorabiliaTitle:vm.itemData.memorabiliaTitle,
          memorabiliaText:vm.itemData.memorabiliaText,
          occurredTime:vm.itemData.occurredTime,
          status:vm.itemData.status?1:0,
          familyId:vm.itemData.familyId,
          //附件上传
          ucode:vm.$route.params.ucode
        },
        success:(data)=>{
          vm.showToast('保存成功！',600,vm.cancel)
        },
        error:()=>{
          vm.showToast('更新失败，请重试')
        },
        complete:()=>{
          vm.setLoading(false)
        }
      })
    },
    uploadSuccess (file,res){
      //根据服务器返回值判断成功与否
      this.showToast(res.info);
    },
    uploadFinished (){
      console.log('finished');
    },
    dateFormat,
    setLoading (isLoading){  this.$store.dispatch('setLoading',isLoading) },
    showToast (toastText,time,callback){  this.$store.dispatch('showToast',{toastText,time,callback}) },
    hideToast (){  this.$store.dispatch('hideToast') }
  }
}
</script>

<style>
/*覆盖bigeventFileList.vue中的样式*/
.app-file-list-item{float: left;width: 100px;height: 100px;float: left;margin: 6px;text-align: center;position: relative;overflow: hidden;box-sizing:border-box;border:1px solid #e3e3e3;background-color: #fefefe;border-radius: 2px}
</style>
